//
// Created by xzy.xiao on 2022/6/8.
//

#include "FindDialog.h"
#include <iostream>
#include <QCheckBox>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>

FindDialog::FindDialog(QWidget *parent) : QDialog(parent) {

    /*
     * 创建组件
     */

    label = new QLabel(tr("Find &what:")); // 快捷键：Alt + w
    lineEdit = new QLineEdit();
    label->setBuddy(lineEdit);

    caseCheckBox = new QCheckBox(tr("Match &case")); // 快捷键：Alt + c
    backwardCheckBox = new QCheckBox(tr("Search &backward")); // 快捷键：Alt + b

    findButton = new QPushButton(tr("&Find")); // 快捷键：Alt + f
    findButton->setDefault(true);
    findButton->setEnabled(false);

    closeButton = new QPushButton(tr("Close"));

    /*
     * 连接信号槽
     */

    connect(lineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(enableFindButton(const QString&)));
    connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked()));
    connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));

    /**
     * 设置布局
     */
    QHBoxLayout *topLeftLayout = new QHBoxLayout;
    topLeftLayout->addWidget(label);
    topLeftLayout->addWidget(lineEdit);

    QVBoxLayout *leftLayout = new QVBoxLayout;
    leftLayout->addLayout(topLeftLayout);
    leftLayout->addWidget(caseCheckBox);
    leftLayout->addWidget(backwardCheckBox);

    QVBoxLayout *rightLayout = new QVBoxLayout;
    rightLayout->addWidget(findButton);
    rightLayout->addWidget(closeButton);
    rightLayout->addStretch();

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addLayout(leftLayout);
    mainLayout->addLayout(rightLayout);
    setLayout(mainLayout);

    setWindowTitle(tr("Find"));
    setFixedHeight(sizeHint().height());
}

FindDialog::~FindDialog() {

}

void FindDialog::findClicked() {
    std::cout << "find button has been clicked...\n";

    QString text = lineEdit->text();
    Qt::CaseSensitivity cs = caseCheckBox->isChecked() ? Qt::CaseInsensitive : Qt::CaseSensitive; // 是否大小写敏感
    // 发送信号
    if (backwardCheckBox->isChecked()) {
        emit findPrevious(text, cs);
    } else {
        emit findNext(text, cs);
    }
}

void FindDialog::enableFindButton(const QString &text) {
    std::cout << "edit text...\n";

    findButton->setEnabled(!text.isEmpty());
}

